<?php

declare(strict_types=1);

namespace Tools\Command;

/**
 * Class Process
 * 
 * You cannot manage processes that the Command Shell is not associated with.
 * @package Tools\Command
 */
class Process 
{
    /**
     * Process ID
     *
     * @var int|string
     */
    private $pid;

    /**
     * Command
     *
     * @var string
     */
    private $command;

    /**
     * Constructor
     *
     * @param boolean $command
     */
    public function __construct($command = false)
    {
        if ($command !== false){
            $this->command = $command;

            $this->runCommand();
        }
    }

    /**
     * Run command
     *
     * @return void
     */
    private function runCommand()
    {
        $command = 'nohup '.$this->command.' > /dev/null 2>&1 & echo $!';

        exec($command, $output);

        $this->pid = (int) $output[0];
    }

    /**
     * Setter
     *
     * @param int|string $pid
     * @return void
     */
    public function setPid($pid)
    {
        $this->pid = $pid;
    }

    /**
     * Getter
     *
     * @return ?int|string
     */
    public function getPid()
    {
        return $this->pid;
    }

    /**
     * Command run status
     *
     * @return bool
     */
    public function status()
    {
        $command = 'ps -p ' . $this->pid;

        exec($command, $output);

        return isset($output[1]);
    }

    /**
     * Run command
     *
     * @return bool
     */
    public function start()
    {
        if (!$this->status()) {
            if (is_string($this->command)) $this->runCommand();
        }

        return $this->status();
    }

    /**
     * Stop command
     *
     * @return bool
     */
    public function stop()
    {
        $command = 'kill -15 ' . $this->pid;

        exec($command);

        return !$this->status();
    }
}

